package com.niknik.deberc.vk;

import com.google.appengine.repackaged.com.google.common.collect.Sets;
import com.niknik.woody.core.IdFactory;
import com.niknik.woody.utils.Check;

import java.util.Set;

import static com.niknik.deberc.vk.VkIdScheme.NO_MORE_IDS;
import static com.niknik.deberc.vk.VkIdScheme.ROOMS_COUNT;

public class VkIdFactory
    implements IdFactory {

  private final Set<String> freeIds = Sets.newHashSet();
  private final Set<String> takenIds = Sets.newHashSet();

  {
    for (Long id = 1L; id <= ROOMS_COUNT; id++) {
      freeIds.add(id.toString());
    }
  }

  @Override
  synchronized public String takeId() {
    Check.state(freeIds.size() != 0, NO_MORE_IDS);

    String id = freeIds.iterator().next();
    freeIds.remove(id);
    takenIds.add(id);
    return id;
  }

  @Override
  synchronized public void freeId(String takenId) {
    if (0 >= Long.parseLong(takenId) || ROOMS_COUNT < Long.parseLong(takenId)) {
      return;
    }

    freeIds.add(takenId);
    takenIds.remove(takenId);
  }
}
